 package com.ikkong.qy.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.formula.ptg.TblPtg;

import com.ikkong.biz.model.Notice;
import com.ikkong.biz.model.NoticeResult;
import com.ikkong.biz.model.Teacher;
import com.ikkong.biz.model.WeixinUser;
import com.ikkong.common.vo.User;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.dao.Db;
import com.ikkong.core.jfinal.ext.kit.JStrKit;
import com.ikkong.qy.core.WeixinAuthInterceptor;
import com.ikkong.qy.core.WeixinBaseController;
import com.ikkong.qy.util.WeixinApi;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

@Before(WeixinAuthInterceptor.class)
public class WeixinNoticeController extends WeixinBaseController {
	public void send() {
		List<Map> noticeDeptList = noticeDeptList(getUser().getId());
		setAttr("nodeList", noticeDeptList);
		render("/weixin/notice/send.html");
	}

	public void doSend() {
		String title = getPara("title");
		String content = getPara("content");

		String teaIds = getPara("teaIds");
		String parIds = getPara("parIds");
		String stuIds = getPara("stuIds");

		WeixinUser user = getUser();

		Notice notice = new Notice();
		notice.setCname(user.getName());
		notice.setCreator(user.getId());
		notice.setTitle(title);
		notice.setContent(content);
		notice.setCtime(new Date());
		
		if (!JStrKit.isBlank(teaIds)) {
			teaIds = teaIds.replaceAll("t_", "");
			if (teaIds.startsWith(",")) {
				teaIds = teaIds.substring(1);
			}
			if (teaIds.endsWith(",")) {
				teaIds = teaIds.substring(0, teaIds.length() - 1);
			}
		}
		if (!JStrKit.isBlank(parIds)) {
			parIds = parIds.replaceAll("d2_", "");
			if (parIds.startsWith(",")) {
				parIds = parIds.substring(1);
			}
			if (parIds.endsWith(",")) {
				parIds = parIds.substring(0, parIds.length() - 1);
			}
		}
		if (!JStrKit.isBlank(stuIds)) {
			stuIds = stuIds.replaceAll("d3_", "");
			if (stuIds.startsWith(",")) {
				stuIds = stuIds.substring(1);
			}
			if (stuIds.endsWith(",")) {
				stuIds = teaIds.substring(0, stuIds.length() - 1);
			}
		}
		
		notice.setParent_auth(parIds);
		notice.setTeacher_auth(teaIds);
		notice.setStudent_auth(stuIds);

		int id = Blade.create(Notice.class).saveRtId(notice);
		if (id > 0) {
			notice.setId(id);
			if (!JStrKit.isBlank(teaIds)) {
				Blade.dao().executeUpdate(
						"call create_notice('" + teaIds + "',1," + id + "," + user.getId() + ",'" + user.getName()
								+ "','" + title + "');", null);
			}
			if (!JStrKit.isBlank(parIds)) {
				Blade.dao().executeUpdate(
						"call create_notice('" + parIds + "',2," + id + "," + user.getId() + ",'" + user.getName()
								+ "','" + title + "');", null);
			}
			if (!JStrKit.isBlank(stuIds)) {
				Blade.dao().executeUpdate(
						"call create_notice('" + stuIds + "',3," + id + "," + user.getId() + ",'" + user.getName()
								+ "','" + title + "');", null);
			}
			WeixinApi.pushNotice(notice);
		}
		
		redirect("/weixinNotice/list?type=2");
	}

	public void list() {
		Integer type = getParaToInt("type");
		Integer customerType = getUserType();
		WeixinUser user = getUser();

		int unreadCount = Db.init().queryInt(
				"select count(1) from tb_notice_result nr where nr.customer_id = " + user.getId()
						+ " and nr.is_read = 0 and nr.customer_type =" + customerType, null);
		setAttr("count", unreadCount);

		if (type == null || customerType != 1) {
			type = 1;
		}

		List<Map> noticeList = null;
		if (type == 2) { // 我发出的
			noticeList = Db
					.init()
					.queryListMap(
							"select n.id,n.title,n.ctime,n.cname,(select count(1) from tb_notice_result nr where nr.notice_id = n.id and nr.is_read =1) as readed,(select count(1) from tb_notice_result nr where nr.notice_id = n.id) as total,t.icon from tb_notice n,tb_teacher t where n.creator = t.id and n.creator = "
									+ user.getId() + " order by n.ctime desc");
		} else { // 我收到的
			noticeList = Db
					.init()
					.queryListMap(
							"select n.id,n.title,n.ctime,n.cname,nr.is_read from tb_notice n,tb_notice_result nr where n.id = nr.notice_id and nr.customer_type = "
									+ customerType
									+ " and nr.customer_id = "
									+ user.getId()
									+ " order by nr.is_read asc, n.ctime desc");
		}
		setAttr("type", type);
		setAttr("noticeList", noticeList);
		render("/weixin/notice/list.html");
	}

	public void view() {
		Integer noticeId = getParaToInt();
		NoticeResult result = Blade.create(NoticeResult.class).findFirst(
				"select nr.* from tb_notice_result nr where nr.customer_id=" + getUser().getId()
						+ " and nr.customer_type = " + getUserType()+" and nr.notice_id = "+noticeId, null);

		
			if(result != null &&result.getIs_read() == 0){
				result.setIs_read(1);
				Blade.create(NoticeResult.class).update(result);
			}

			Notice notice = Blade.create(Notice.class).findById(noticeId);
			setAttr("notice", notice);
			if(notice.getCreator() != getUser().getId()){
				WeixinUser creator =  Blade.create(Teacher.class).findById(notice.getCreator());
				setAttr("creator", creator);
			}
			render("/weixin/notice/view.html");
		
			
	}

	public void loadNoticeRest() {
		Integer page = getParaToInt("page", 1);
		Integer row = getParaToInt("row", 20);
		Integer noticeId = getParaToInt("noticeId");

		int total = Db.init().queryInt("select count(1) from tb_notice_result nr where nr.notice_id = " + noticeId,
				null);
		List<Map> data = new ArrayList<>();
		if ((page - 1) * row < total) {
			data = getNoticeRestData(page, row, noticeId);
		}

		// int total = 100;
		// for(int i = 0;i<20;i++){
		// Map<String, Object> temp = new HashMap<String, Object>();
		// temp.put("is_read", i%2);
		// temp.put("ctime", new Date());
		// temp.put("name", "t"+page+"_"+i);
		// temp.put("icon", null);
		// temp.put("customer_type", i%3);
		// temp.put("mobile", "13800000"+page+"_"+i);
		// data.add(temp);
		// }

		Map<String, Object> res = new HashMap<>();
		res.put("total", total);
		res.put("data", data);
		renderJson(res);
	}

	private List<Map> getNoticeRestData(int page, int row, Integer noticeId) {
		List<Map> resList = Db
				.init()
				.queryListMap(
						"select nr.is_read,nr.ctime,v.name,v.icon,nr.customer_type,v.mobile from tb_notice_result nr,v_weixin_users v where nr.notice_id = "
								+ noticeId
								+ " and nr.customer_type = v.type and nr.customer_id = v.id order by customer_type asc,customer_id asc limit "
								+ (page - 1) * row + "," + row);
		return resList;
	}

	private List<Map> noticeDeptList(Integer userId) {
		List<Map> teacherDeptList = Db
				.init()
				.queryListMap(
						"select d.id,d.fullname as name,d.pid,'d1' as type from tfw_dept d,tb_teacher t1,tb_auth_tag at,tb_teacher t2 where t2.id ="
								+ userId
								+ " and t2.notice_tag_id = at.id and at.teacher_auth like concat('%,',t1.id,',%') and t1.depts like concat('%,',d.id,',%') and d.type = 1 group by d.id order by d.id asc");
		List<Map> teacherList = Db
				.init()
				.queryListMap(
						"select t1.id,t1.name,t1.depts as pid,'t' as type from tb_teacher t1,tb_auth_tag at,tb_teacher t2 where t2.id ="
								+ userId
								+ " and t2.notice_tag_id = at.id and at.teacher_auth like concat('%,',t1.id,',%') group by t1.id order by t1.id asc");

		List<Map> resList = new ArrayList<>();
		resList.addAll(teacherDeptList);
		resList.addAll(teacherList);

		List<Map> parentDeptList = Db
				.init()
				.queryListMap(
						"select d.id,d.fullname as name,d.pid,'d2' as type from tfw_dept d,tb_auth_tag at,tb_teacher t2 where t2.id ="
								+ userId
								+ " and t2.notice_tag_id = at.id and at.parent_auth like concat('%,',d.id,',%') and d.type = 2 group by d.id order by d.id asc");
		if (parentDeptList != null && parentDeptList.size() > 0) {
			Map<String, Object> temp = new HashMap<String, Object>();
			temp.put("id", 1002);
			temp.put("name", "所有家长");
			temp.put("pid", "1");
			temp.put("type", "d1");
			resList.add(temp);
			resList.addAll(parentDeptList);
		}

		List<Map> studentDeptList = Db
				.init()
				.queryListMap(
						"select d.id,d.fullname as name,d.pid,'d3' as type from tfw_dept d,tb_auth_tag at,tb_teacher t2 where t2.id ="
								+ userId
								+ " and t2.notice_tag_id = at.id and at.student_auth like concat('%,',d.id,',%') and d.type = 3 group by d.id order by d.num asc,d.id asc");
		if (studentDeptList != null && studentDeptList.size() > 0) {
			Map<String, Object> temp = new HashMap<String, Object>();
			temp.put("id", 1001);
			temp.put("name", "所有学生");
			temp.put("pid", "1");
			temp.put("type", "d1");
			resList.add(temp);
			resList.addAll(studentDeptList);
		}

		return resList;
	}
}
